package com.avocado.base.validator;


import com.avocado.base.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


@Slf4j
public class UserCurrentPasswordValidator implements ConstraintValidator<UserCurrentPasswordValidation, String> {



    public static PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
    private final UserService userService;

    public UserCurrentPasswordValidator( UserService userService) {

        this.userService = userService;
    }


    @Override
    public void initialize(UserCurrentPasswordValidation constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        try {

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            // 获取当前登录用户
            Object principal = authentication.getPrincipal();

            if (principal instanceof String) {

                String username = (String)principal;

                String oldEncodePassword=userService.findByName(username).getPassword();

                return passwordEncoder.matches(value,oldEncodePassword);

            }

        } catch (Exception ex) {
            log.error(ex.getLocalizedMessage());
        }
        return false;
    }
}
